#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re

class LrcParser:
    def __init__(self):
        """
        
        Arguments:
        - `self`:
        """
        self.orig_text = ""
        self.offset    = 0
        self.result    = []

    def set_text(self, text):
        """
        
        Arguments:
        - `self`:
        - `text`:
        """
        self.orig_text = text

    def parse(self):
        """parse the original lrc text to offset and result.
        
        Arguments:
        - `self`:
        """
        # parse the offset field
        m = re.search(r'\[offset:([-+]?\d+)\]', self.orig_text)
        if m:
            self.offset = int(m.group(1))
            print "used offset %d" % self.offset

        # parse lyrics
        # just support the simple format
        # [mm:ss.xx]+ text
        # [mm:ss]+ text
        self.result = []
        lines = self.orig_text.splitlines()
        p = re.compile(r'\[(\d+):(\d+)(\.\d+)?\]')
        for line in lines:
            times = []
            while True:
                m = p.match(line)
                if not m:
                    break
                # get the .xx part
                xx = m.group(3)
                if xx is not None > 0:
                    ms = int(xx[1:]) * 10
                else:
                    ms = 0
                times.append((int(m.group(1)) * 60 * 1000) + (int(m.group(2)) * 1000) + ms)
                line = line[m.end():]
            if len(times) > 0:
                for t in times:
                    self.result.append((t - self.offset, line.strip()))

        self.result.sort(lambda x, y: cmp(x[0], y[0]))

        return self.result

if __name__ == '__main__':
    try:
        fp = open("test.lrc")
    except:
        print "open test.lrc failed"
    else:
        text = fp.read()
        parser = LrcParser(text)
        parser.parse()
        print "offset =", parser.offset
        for item in parser.result:
            print item[0], item[1]
